package com.zzq.my.jetpacks.net.base
import com.blankj.utilcode.util.SPUtils
import com.zzq.my.jetpacks.net.entity.*
/**
 * 描述：网络请求统一处理
 * 作者：zhuangzeqin
 * 时间: 2021/11/5-14:20
 * 邮箱：zzq@eeepay.cn
 * 备注:
 */
open class BaseRepository {
    //标准的格式
    suspend fun <T> executeHttp(block: suspend () -> ApiResponse<T>): ApiResponse<T> {
        runCatching {
            block.invoke()//协程代码块
        }.onSuccess { data: ApiResponse<T> ->
            return handleHttpOk(data)//成功
        }.onFailure { e ->
            //Status Code: 非200
            return handleHttpError(e)//失败
        }
        return ApiEmptyResponse()//返回空
    }
    //返回整个实体包括body + head 头部
    suspend fun <T> executeBeanHttp(block: suspend () -> T): T? {
        runCatching {
            block.invoke()//协程代码块
        }.onSuccess { data ->
            return data//成功
        }.onFailure { e ->
            //Status Code: 非200
            e.printStackTrace()
            handlingExceptions(e)
            return null//返回空
        }
        return null//返回空
    }


    /**
     * 返回200，但是还要判断isSuccess
     */
    private fun <T> handleHttpOk(data: ApiResponse<T>): ApiResponse<T> {
        return if (data.success == true && data.code == 200) {//成功
            getHttpSuccessResponse(data)
        } else {
            handlingApiExceptions(data.code, data.message)
            ApiFailedResponse(data.code, data.message, data.data, data.count)
        }
    }

    /**
     * 非后台返回错误，捕获到的异常
     */
    private fun <T> handleHttpError(e: Throwable): ApiErrorResponse<T> {
        e.printStackTrace()
        handlingExceptions(e)
        return ApiErrorResponse(e)
    }

    /**
     * 成功和数据为空的处理
     */
    private fun <T> getHttpSuccessResponse(response: ApiResponse<T>): ApiResponse<T> {
        val code = response.code
        val message = response.message
        val data = response.data
        val count = response.count
        //数据为空的处理
        return if ((data is String && (data as String).isEmpty()) || data == null || data is List<*> && (data as List<*>).isEmpty()) {
            ApiEmptyResponse()
        } else {
            ApiSuccessResponse(code, message, data, count)
        }
    }
    /**
     * 公共参数
     *
     * @return
     */
    @Synchronized
    open fun getPubParams():MutableMap<String, String> {
        val pubParams: MutableMap<String, String> = mutableMapOf()
        val agentNo: String = SPUtils.getInstance("SPUtils").getString("agent_no","0")
         //代理商编号
        pubParams["agent_no"] = agentNo //当前登录代理商编号,必填
        pubParams["agentNo"] = agentNo //当前登录代理商编号,必填 后台定义的字段不一样
        pubParams["curAgentNo"] = agentNo //当前登录代理商编号,必填 后台定义的字段不一样
        return pubParams
    }
}